# 新闻详情相关的视图函数
from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    # else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/news_list', methods=["POST"])
@user_login_data
def news_list():
    """用户新闻列表"""
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}

    return render_template('news/user_news_list.html', data=data)



@news_blu.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():
    """评论点赞"""

    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    comment_id = request.json.get("comment_id")
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 判断参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")

    if action == "add":
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
            db.session.add(comment_like)
            # 增加点赞条数
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 减小点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    """新闻评论后端逻辑"""
    # 1 从提交的请求中判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.DATAERR, errmsg="用户未登录")
    # 2 获取detail.js文件提交的数据
    data_json = request.json
    news_id = data_json.get("news_id")
    comment_str = data_json.get("comment")
    parent_id = data_json.get("parent_id")
    # print(news_id,comment_str)
    # 3 判断数据是否齐全
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="请求参数不全")

    # 4 根据获取到的用户取查询这个新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")

    # 5 把评论信息添加到用户身上
    comment = Comment()
    comment.user_id = user.id
    comment.content = comment_str
    comment.news_id = news_id
    if parent_id:
        comment.parent_id = parent_id

    # 提交comment数据，验证细节
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    # 已设置讲数据自动保存到数据库
    # print(comment.to_dict())
    # 6 一切正常返回 ok
    return jsonify(errno=RET.OK, errmsg="评论成功",data=comment.to_dict())



@news_blu.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    """新闻收藏处理后端"""
    # 1 获取请求参数
    user = g.user
    json_data = request.json
    news_id = json_data["news_id"]
    active = json_data["active"]
    # 2 判断各种错误情况，做出错误返回
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户还没登录")

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if active not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 从数据看查询数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")


    # 3 判断是要收藏还是取消收藏，做出相应处理
    if active == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    # 4 提交退数据做出的处理
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    # 1 查询新闻数据并返回
    try:
        news = News.query.get(news_id)
        print(news_id)
        print(news)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    # print(news_id)
    # print(news.id)
    if not news:
        # 返回数据未找到的页面
        abort(404)

    # 2. 查询新闻点击量数据并展示
    # 数据库按点击率排序查询
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    # 3. 判定新闻是否被收藏，默认没有收藏
    is_collected = False
    is_followed = False

    # 判断是否登录 如果登录了通过关联查询看当前新闻是否是数据登录用户
    # 用户登录 and 新闻属于该用户才去过滤
    # 判断用户是否关注过新闻的作者
    # is_followed = False
    # 用户需要登录,并且新闻要有作者
    # if g.user and news.user:
        # 用户必须要在作者的  粉丝列表中
        # if g.user in news.user.followers:
        #     is_followed = True

    if g.user and news.user:
        if news in g.user.collection_news:
            is_collected = True
        if news.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed = True
    # 4 获取当前新闻的评论
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    # print(comments)
    # 5 获取新闻点赞id 列表
    comment_like_ids = []
    if g.user:
        # 如果当前用户已登录
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 取到当前用户在当前新闻的所有评论点赞的记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == g.user.id).all()
                # 取出记录中所有的评论id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    # 6 添加到列表里面 当前用户的 本条新闻里的某一个点赞数量
    comment_list = []
    for item in comments if comments else []:
        # print(item)
        comment_dict = item.to_dict()
        comment_dict["is_like"] = False
        # 判断用户是否点赞该评论
        if g.user and item.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)



    news.clicks += 1
    data = {
        "news": news.to_dict(),
        "user_info": g.user.to_dict() if g.user else None,
        "click_news_list": click_news_list,
        "is_collected": is_collected,
        "comments": comment_list,
        "is_followed": is_followed
    }
    return render_template("news/detail.html", data=data)
